<template>
    <div>
      <div style="width: 95%;margin: 10px auto">
      <div class="card" >
        <el-input v-model="data.key" clearable style="width: 200px;margin-right: 10px" placeholder="请输入名称"/>
        <el-button type="warning" plain @click="load(data.key)">搜索</el-button>
      </div>
        <el-row :gutter="10">
          <el-col :span="18">
            <div class="card" style="margin-top: 5px" >
              <el-table :data="data.tableData" :row-key="getRowKeys" @selection-change="handleSelectionChange" min-height="250" style="width: 100%">
                <el-table-column type="selection" :reserve-selection="true" width="55" />
                <el-table-column label="图片">
                  <template #default="scope">
                    <el-image @click="rouer.push('goodsDateil?id='+scope.row.goodsid)"
                        style="width: 50px; height: 50px"
                        :src="scope.row.goods.fileimg"
                        :preview-src-list="[scope.row.goods.fileimg]"
                        :preview-teleported="true">
                    </el-image>
                  </template>
                </el-table-column>
                <el-table-column prop="goodsname" label="名称" />
                <el-table-column label="价格">
                  <template #default="scope">
                    <h4 style="color: #ff0808;margin: 0">
                      <template v-if="scope.row.goods.tjprice>0">
                        <span class="strike">￥{{scope.row.goods.price}}</span>
                        <span style="margin-left: 10px">￥{{scope.row.goods.tjprice}}</span>
                      </template>
                      <template v-else>
                        <span>￥{{scope.row.goods.price}}</span>
                      </template>
                    </h4>
                  </template>
                </el-table-column>
                <el-table-column label="数量">
                  <template #default="scope">
                    <el-input-number @change="handleChange(scope.row,data.valsAll)" size="small" :min="1" :max="scope.row.kcnum" v-model="scope.row.slnum"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column prop="heji" label="小计" />
                <el-table-column label="操作" >
                  <template #default="scope">
                    <el-button type="danger" plain size="small" @click="Delete(scope.row.id)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>

              <div v-if="data.total>0" style="display: flex;justify-content: center;margin: 15px auto">
                <el-pagination
                    @current-change="load()"
                    background
                    layout="prev, pager, next"
                    v-model:page-size="data.pageSize"
                    v-model:current-page="data.pageNum"
                    :total="data.total"/>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="card" style="margin-top: 5px">
              <div style="float: left;color: #888888FF;">
                <p>已 选 商 品：{{data.valsAll.length}} 个</p>
                <p>合 计 金 额：<strong style="color: #ff5000;font-size: 20px;">{{data.subtotal}} 元</strong></p>
              </div>
              <el-button v-if="data.valsAll.length>0" @click="Add" type="danger" style="width: 100%;margin-top: 70px;">提交订单</el-button>
              <el-button v-else disabled type="danger" style="width: 100%;margin-top: 70px;">请选择菜品</el-button>
            </div>
          </el-col>
        </el-row>
      </div>
      <el-drawer v-model="data.formVisible" :before-close="handleClose"  size="40%" :with-header="false">
        <h3 style="text-align: center">{{data.title}}</h3>
        <el-form :model="data.form" ref="formRef" :rules="data.rules" label-width="120px" style="padding: 20px">
          <el-form-item label="联系人" prop="name">
            <el-input v-model="data.form.name" placeholder="请输入联系人"/>
          </el-form-item>
          <el-form-item label="联系方式" prop="tel">
            <el-input v-model="data.form.tel" placeholder="请输入联系方式"/>
          </el-form-item>
          <el-form-item label="就餐人数" prop="slnum">
            <el-input type="number" :min="1" v-model="data.form.slnum" placeholder="请输入就餐人数"/>
          </el-form-item>
        </el-form>
        <template #footer>
      <span class="dialog-footer">
        <el-button @click="data.formVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">保 存</el-button>
      </span>
        </template>

      </el-drawer>

    </div>
</template>

<script setup>
import {createApp, onMounted, reactive, ref} from "vue";
import request from '@/utils/request.js'
import {ElMessage, ElMessageBox} from "element-plus";
import qs from "qs";
import {useRouter} from "vue-router";
const rouer = useRouter()
//提交是表单校验
const formRef = ref()
//关闭弹框回调函数
const handleClose = () => {
  ElMessageBox.confirm('是否确认需要关闭当前窗口?')
      .then(() => {
        data.formVisible = false
      })
      .catch(() => {
      })
}

const data = reactive({
  member: JSON.parse(localStorage.getItem('member') || '{}'),
  key:'',
  key1:'',
  pageNum: 1,
  pageSize: 10,
  total: 0,
  formVisible: false,
  form: {},
  tableData:[],
  title:'',
  ids:[],
  addrlist:[],
  valsAll:[],
  subtotal:0,
  rules:{
    name: [{ required: true, message: '联系人不能为空', trigger: 'blur' },],
    tel: [{ required: true, message: '联系方式不能为空', trigger: 'blur' },],
    slnum: [{ required: true, message: '就餐人数不能为空', trigger: 'blur' },],
  }
})
//查询分类列表
const getclist=()=>{
request.post('addrListAll',qs.stringify({
  memberid:data.member.id
})).then(res=>{
  data.addrlist = res.data
})
}

//信息列表
const load =()=>{
  request.post('/cart/list', qs.stringify({
    memberid:data.member.id,
    key:data.key,
    pageNum: data.pageNum,
    pageSize: data.pageSize,
  })).then(res => {
    data.tableData = res.data.list
    data.total = res.data.total
  })
}
//编辑购物车菜品数量
const handleChange = (row,vals) =>{
  if(row.slnum > row.kcnum){ElMessage({ message: '操作失败，已达库存上限', grouping: true, type: 'error',});return false;}
  request.post('/cart/edit', qs.stringify({
    id:row.id,
    slnum:row.slnum,
  })).then(res => {
    if (res.code === '200') {
      ElMessage({ message: '操作成功', grouping: true, type: 'success'})
      load()
    } else {
      ElMessage.error(res.msg)
    }
  })
  //调用计算选中菜品合计方法
  if (data.valsAll.length>0){
    data.valsAll = data.valsAll.map(item=>{
      if (item.id===row.id){
        item.slnum = row.slnum
      }
    })
    handleSelectionChange(vals)
  }
}
//解决跨分页选中后分页取消的情况
const getRowKeys = (row)=>{
  return row.id;
}

//选中需要删除的对象
const handleSelectionChange = (val)=>{
  data.valsAll = val;
  //计算选中菜品的总价
  let subtotal = 0;
  let price = 0;
  for (let i = 0; i < data.valsAll.length; i++) {
    //console.log('数量===',this.valsAll[i].slnum)
    if (data.valsAll[i].goods.tjprice>0){
      price = data.valsAll[i].goods.tjprice;
    }else{
      price = data.valsAll[i].goods.price;
    }
    subtotal += data.valsAll[i].slnum*price;
  }
  data.subtotal = subtotal;
}


// 订单信息新增
const Add = () => {
  data.form = data.member
  data.formVisible = true
  data.title='订单新增'
}

// 订单新增
const save = () => {
  formRef.value.validate((valid=>{
    if(!/^[1][3,4,5,7,8,9][0-9]{9}$/.test(data.form.tel)){ElMessage.error("电话号码格式有误");return ;}
    if(valid){
    let ids = data.valsAll.map(item => item.id).join()
    request.post('ordermsgAdd', qs.stringify({
      memberid:data.member.id,
      name:data.form.name,
      tel:data.form.tel,
      slnum:data.form.slnum,
      vals:ids
    })).then(res => {
      if (res.code === '200') {
        ElMessage.success('操作成功')
        data.formVisible = false
        load()
        data.valsAll=[]
        data.subtotal=0
      } else {
        ElMessage.error(res.msg)
      }
    })
    }
  }))
}

// 删除
const Delete = (id) => {
  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗?', { type: 'warning' }).then(res => {
    request.post('/cart/del?id=' + id).then(res => {
      if (res.code === '200') {
        load()
        ElMessage.success('操作成功')
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(err => {})
}



getclist()
load()

/*onMounted(() => {
  load(data.pageNum)
})*/

</script>
<style scoped>
</style>
